const mysql = require('mysql');
const db = require('./mysqlConfig');

exports.getOrderHistoryByUserId = (user_id, callback) => {
    const sql = `
        SELECT 
            o.order_id,
            o.billiard_room_id,
            o.room_id,
            o.start_time,
            o.end_time,
            o.total_time,
            o.amount,
            o.created_time,
            o.status,
            o.payment_type,
            br.room_name AS shop_name,
            rt.table_number,
            r.rating,
            r.comment,
            r.images,
            r.created_at AS review_created_at
        FROM orders o
        LEFT JOIN billiard_rooms br ON o.billiard_room_id = br.room_id
        LEFT JOIN room_table rt ON o.room_id = rt.table_id
        LEFT JOIN reviews r ON o.order_id = r.order_id
        WHERE o.user_id = ? AND o.status IN ('reviewed', 'refunded', 'completed')
        ORDER BY o.created_time DESC;
    `;
    db.query(sql, [user_id], (error, results) => {
        if (error) return callback(error, null);
        callback(null, results);
    });
};

exports.submitReview = (reviewData, callback) => {
    const { order_id, rating, comment, images } = reviewData;

    const sql = 'INSERT INTO reviews (order_id, rating, comment, images) VALUES (?, ?, ?, ?)';
    db.query(sql, [order_id, rating, comment, JSON.stringify(images)], (error, result) => {
        if (error) return callback(error, null);

        // 更新订单状态为 reviewed
        const updateOrderStatus = 'UPDATE orders SET status = ? WHERE order_id = ?';
        db.query(updateOrderStatus, ['reviewed', order_id], (err) => {
            if (err) return callback(err, null);
            callback(null, { ...reviewData });
        });
    });
};
